<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use App\Models\CompanyComment;
use App\Models\Company;
use Illuminate\Support\Facades\DB;

class CompanyCommentController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        if(!$this->user->can('viewCompanyComment')) abort(405);
            
        /*搜索处理*/
        $keywords = $request->input('keywords', '');
        $comments = CompanyComment::where('content', 'LIKE', "%$keywords%")->where('to_comment_id','=',0)->paginate(20);
        return view('admin.enterprise.comment.index')->with('comments', $comments);
    }

    /**
     * Remove the specified resource from storage.
     * @param  int  $id
     * @return Response
     */
    public function destroy(Request $request)
    {
//        if(!$this->user->can('deleteCompanyComment'))
//            return $this->formatJson('error',$this->permerror);
        
        $id = $request->input('comment_id');
        $comment = CompanyComment::find($id);
        if(empty($comment))
        {
            return  $this->formatJson('falied','抱歉，资源不存在!');
        }
        else
        {
            DB::beginTransaction();
            try{
                //删除子评论
                CompanyComment::where('to_comment_id', '=', $comment->comment_id)->delete();
                if($comment->job_id == 0){  //删除企业评论时评论数减一
                    $comp = Company::findOrNew($comment->company_id);
                    $comp->decrementDel('comments_num',1);
                }
                $comment->delete();
                DB::commit();
            }catch (\PDOException $e){
                DB::rollback();
                return $this->formatJson('falied','评论删除失败');
            }
            return $this->formatJson('success','评论删除成功！');
        }
    }

    /**
     * Remove the specified resource from storage.
     * @param  int  $id
     * @return Response
     */
    public function batchDelete(Request $request)
    {
        if(!$this->user->can('deleteCompanyComment'))
            return $this->formatJson('error',$this->permerror);
        
        $ids = explode(',', $request->input('comment_id'));
        $bbs_comment = CompanyComment::whereIn('comment_id', $ids);
        $count = $bbs_comment->count();
        if ($bbs_comment->delete())
            return  Response::json(array('status'=>'success','msg'=>'成功删除 [' . $count . ']条 评论'));
        else
            return  Response::json(array('status'=>'error','msg'=>'删除失败'));
    }
}
